import React from 'react';
import {Form, Row, Col, Button, DatePicker} from 'antd';
import {withRouter} from 'react-router-dom';
import Grid from '../../components/table/grid';
import tranStartType from '../../utils/tranStartType';
import {sessionManager} from '../../utils/sessionStorage';
import {injectIntl} from 'react-intl';
import moment from 'moment';
import axios from 'axios';

const FormItem = Form.Item;
const createForm = Form.create;
const { RangePicker} = DatePicker;

@withRouter
class chargeOrder extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            params: {
                qryType: 0,
                chargeEndTimeStart: moment().subtract('days', 31).format('YYYY.MM.DD 00:00:00'),
                chargeEndTimeEnd: moment().format('YYYY.MM.DD 23:59:00'),
                stubGroupId: sessionManager.get('selectStuGroup').id,
                stubId: ''
            },
            searchQuest: "",
            gridStyle:{
                scroll:true
            },
            refresh: 0
        };
        const common = this.props.intl.messages.common;
        this.columns = [
            {
                title: common.orderNO,
                dataIndex: 'id',
                key: 'id',
                className:'SC-col-dots',
                width:250
            },
            {
                title: common.startTime,
                dataIndex: 'startTime',
                key: 'startTime',
                className:'SC-col-dots',
                width:250
            },
            {
                title: common.endTime,
                dataIndex: 'endTime',
                key: 'endTime',
                className:'SC-col-dots',
                width:250

            },
            {
                title: common.duration,
                dataIndex: 'chargeTime',
                key: 'chargeTime',
                className:'SC-col-dots',
                width:150
            },
            {
                title: common.electricQuantity,
                dataIndex: 'electric',
                key: 'electric',
                className:'SC-col-dots',
                width:150
            },
            {
                title: common.energyCharge,
                dataIndex: 'feeElectric',
                key: 'feeElectric',
                className:'SC-col-dots',
                width:150
            },
            {
                title: common.serviceCharge,
                dataIndex: 'feeService',
                key: 'feeService',
                className:'SC-col-dots',
                width:150
            },
            {
                title: common.chargingState,
                dataIndex: 'status',
                key: 'status',
                className:'SC-col-dots',
                width:200
            },
            {
                title: common.startType,
                dataIndex: 'startType',
                key: 'startType',
                className:'SC-col-dots',
                width:200
            },
            {
                title: common.endInfo,
                dataIndex: 'endInfo',
                key: 'endInfo',
                className:'SC-col-dots',
                width:220,
                fixed: 'right',
            },
        ];
    }

    transformData = (data) => {
        const common = this.props.intl.messages.common;
        data.forEach((item, index) => {
            if (item.status === 1) {
                for (let key of Object.keys(item)) {
                    if (key !== "id") {
                        item[key] = ""
                    }
                }
            } else {
                item.status = common.chargingCompleted;
                item.startType = tranStartType(item.startType)
            }
            return item
        });
        return data
    }
    // sendSword=()=> {
    //     this.refs.test.handleTableChange();
    // }

    obj2getParam = (values) => {
        var params = ``;
        for (let key of Object.keys(values)) {
            if (typeof values[key] !== "undefined") {
                console.log(key, values[key]);
                params += `${key}=${values[key]}&`
            }
        }
        this.setState({
            searchQuest: params
        })
    }
    //提交表格验证
    handleSubmit = (e) => {
        e.preventDefault();
        this.props.form.validateFields((errors, values) => {
            if (errors) {
                console.log('Errors in form!!!');
                return;
            }
            console.log('Submit!!!', values);
            let chargeEndTimeStart = values.startTime[0].format('YYYY.MM.DD 00:00:00');
            let chargeEndTimeEnd = values.startTime[1].format('YYYY.MM.DD 23:59:00');
            let stubGroupId = sessionManager.get('selectStuGroup').id;
            let params = {
                chargeEndTimeStart,
                chargeEndTimeEnd,
                stubGroupId,
                qryType: 0
            }
            this.obj2getParam(params)
            this.setState({
                params: {...params},
                refresh: this.state.refresh + 1
            });
        });
    }

    render() {
        let locale=sessionManager.get('locale');
        this.state.searchQuest = `qryType=${this.state.params.qryType}&chargeEndTimeStart=${this.state.params.chargeEndTimeStart ? this.state.params.chargeEndTimeStart : ''}&chargeEndTimeEnd=${this.state.params.chargeEndTimeEnd ? this.state.params.chargeEndTimeEnd : ''}&stubGroupId=${this.state.params.stubGroupId ? this.state.params.stubGroupId : ''}&locale=${locale}`;
        const { getFieldDecorator} = this.props.form;
        const dateFormat = 'YYYY.MM.DD';
        const formItemLayout = {
            labelCol: {span: 8},
            wrapperCol: {span: 16},
        };
        const common = this.props.intl.messages.common;
        const config = {
            rules: [{type: 'array', required: true, message: '请选择时间!'}],
            // initialValue:moment(formDate.YMD(new Date()), dateFormat);
            initialValue: [moment(this.state.params.chargeEndTimeStart, dateFormat), moment(this.state.params.chargeEndTimeEnd, dateFormat)]
        };
        const token=(JSON.parse(sessionStorage.getItem("token"))||{}).token;
        return (
            <div>
                <form form={this.props.form}>
                    <Row gutter={16}>
                        <Col xxl={5} xl={8}>
                            <FormItem
                                {...formItemLayout}
                                label={common.dateQuery}
                            >
                                {getFieldDecorator('startTime', config)(
                                    <RangePicker format={dateFormat} placeholder="日期查询"/>
                                )}
                            </FormItem>
                        </Col>
                        <Col span={10}>
                            <FormItem>
                                <Button type="primary" icon="search" onClick={this.handleSubmit}
                                        style={{marginRight: 8}}>{common.search}</Button>
                                <a href={`${axios.defaults.baseURL}/api/order/list/export?${this.state.searchQuest}&token=${token}`}>
                                    <Button type="primary">{common.exportStatement}</Button>
                                </a>
                            </FormItem>
                        </Col>
                    </Row>
                </form>
                <Grid gridStyle={this.state.gridStyle} transformData={this.transformData} refresh={this.state.refresh} params={this.state.params}
                      columns={this.columns} url="api/order/list/qry"/>
            </div>
        )
    }
}

//ant 表格验证需要创建表格-createForm
chargeOrder = createForm()(chargeOrder);
export default injectIntl(chargeOrder);